import { defineStore } from 'pinia';
import { to } from 'await-to-js';

import { getInfo as getUserInfo, login as loginApi, logout as logoutApi } from '@/api/login';
import type { LoginData } from '@/api/types';
import { getToken, removeToken, setToken } from '@/utils/auth';
import store from '@/store';
import defaultAvatar from '@/assets/images/profile.jpg';

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref(getToken());
    const name = ref('');
    const nickname = ref('');
    const userId = ref<string | number>('');
    const tenantId = ref<string>('');
    const avatar = ref('');
    // 用户角色编码集合 → 判断路由权限
    const roles = ref<string[]>([]);
    // 用户权限编码集合 → 判断按钮权限
    const permissions = ref<string[]>([]);

    /**
     * 登录
     * @param userInfo
     */
    const login = async (userInfo: LoginData): Promise<void> => {
      const [err, res] = await to(loginApi(userInfo));
      if (res) {
        const data = res.data;
        setToken(data.access_token);
        token.value = data.access_token;
        return Promise.resolve();
      }
      return Promise.reject(err);
    };

    /**
     * 获取用户信息
     */
    const getInfo = async (): Promise<void> => {
      const [err, res] = await to(getUserInfo());

      if (res) {
        const data = res.data;
        const user = data.user;
        const profile = user.avatar == '' || user.avatar == null ? defaultAvatar : user.avatar;

        if (data.roles && data.roles.length > 0) {
          // 验证返回的roles是否是一个非空数组
          roles.value = data.roles;
          permissions.value = data.permissions;
        } else {
          roles.value = ['ROLE_DEFAULT'];
        }
        name.value = user.userName;
        nickname.value = user.nickName;
        avatar.value = profile;
        userId.value = user.userId;
        tenantId.value = user.tenantId;
        return Promise.resolve();
      }
      return Promise.reject(err);
    };

    /**
     * 设置头像
     * @param value
     */
    const setAvatar = (value: string) => {
      avatar.value = value;
    };

    /**
     * 注销
     */
    const logout = async (): Promise<void> => {
      await logoutApi();
      token.value = '';
      roles.value = [];
      permissions.value = [];
      removeToken();
    };

    return {
      userId,
      tenantId,
      token,
      nickname,
      avatar,
      roles,
      permissions,
      login,
      getInfo,
      logout,
      setAvatar,
    };
  },
);

export default useUserStore;

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
